//
//  WNDrawVC.swift
//  WalkNovel
//
//  Created by Kevin on 21/3/2023.
//

import UIKit
import Lottie

class WNDrawVC: WNBaseVC {
    
    deinit {
        loopView.removeTimer()
    }
    
    lazy var bgView: UIImageView = {
        var view = UIImageView(image: UIImage(named: "reward_bg"))
        view.contentMode = .scaleAspectFill
        return view
    }()
    
    lazy var loopView: LoopView = {
        var view = LoopView()
        return view
    }()
    
    lazy var goldView: GoldView = {
        var view = GoldView()
        return view
    }()
    
    lazy var animationView: LottieAnimationView = {
        var view = LottieAnimationView()
        view.shouldRasterizeWhenIdle = true
        view.isHidden = true
        return view
    }()

    lazy var drawView: DrawView = {
        let view = DrawView()
        view.delegate = self
        return view
    }()
    
    var rid: Int = 2
    
    var userArr = [LotteryModel]() {
        didSet {
            loopView.modelArr = userArr
            loopView.startLoopView()
        }
    }
    
    var prizeArr = [LotteryModel]() {
        didSet {
            drawView.set(lotteries: prizeArr)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        view.addSubview(bgView)
        view.addSubview(loopView)
        view.addSubview(goldView)
        view.addSubview(drawView)
        view.addSubview(animationView)
        bgView.snp.makeConstraints { make in
            make.top.left.bottom.right.equalTo(0)
        }
        loopView.snp.makeConstraints { (make) in
            make.top.equalTo(NaviTotalHeight+24)
            make.left.equalTo(scaleWidth(54))
            make.right.equalTo(-scaleWidth(54))
            make.height.equalTo(40)
        }
        goldView.snp.makeConstraints { (make) in
            make.top.equalTo(loopView.snp.bottom).offset(24)
            make.left.equalTo(scaleWidth(64))
            make.right.equalTo(-scaleWidth(64))
            make.height.equalTo(40)
        }
        drawView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(goldView.snp.bottom).offset(16)
            make.width.equalTo(302)
            make.height.equalTo(331)
        }
        animationView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(drawView.snp.bottom)
            make.width.equalTo(320)
            make.height.equalTo(320)
        }
        navView.backgroundColor = .clear
        view.bringSubviewToFront(navView)
    }
    
    override func dataConfig() {
        pageName = "Luck Giveaway"
        navView.titleName = "LUCKY GIVEAWAY"
        navView.rightBtnTitle = "RULE"
        navView.rightClosure = { [weak self] in
            self?.wn_pushWebVC(WNConfigure.WNURL.wn_DrawRule, "Draw Rule")
        }
        prizeRequest()
        awardUserRequest()
        getUserGold { [weak self] gold in
            self?.goldView.goldCount.text = "\(gold) Golds"
        }
    }
}

extension WNDrawVC: DrawViewDelegate {
    
    func lottery(_ completion: @escaping ((Bool, Award) -> Void)) {
        guard WNSingleData.shared.userGold >= 50 else {
            wn_toast("Gold balance not enough")
            return
        }
        provider_Rank.rx.request(.draw)
            .asObservable().mapModel(BaseModel<LotteryModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    completion(false, Award(id: 0))
                    return
                }
                if let data = model.data {
                    self?.rid = data.status
                    completion(true, Award(id: self?.rid ?? 0))
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
                completion(false, Award(id: 0))
            }).disposed(by: rx.disposeBag)
    }
    
    func animationDidStart(_ anim: CAAnimation) {
    }
    
    func animationDidStop(_ anim: CAAnimation) {
        WNThread.wn_runInMainThread {
            self.handleAnimation()
        }
    }
    
    func handleAnimation() {
        if let m = prizeArr.first(where: {$0.id == rid}) {
            if m.gold != 0 {
                WNHUD.wn_show("Win \(m.wheelName ?? "")", 3, animationView)
            }
            animationView.animation = LottieAnimation.named(m.gold == 0 ? "not_win" : "congratulate")
            animationView.isHidden = false
            animationView.play { (finsihed) in
                if finsihed {
                    self.animationView.isHidden = true
                }
            }
            winDrawRequest(m.id)
        }
    }
}

extension WNDrawVC {
    
    func prizeRequest() {
        provider_Rank.rx.request(.prizeList)
            .asObservable().mapModel(BaseModel<[LotteryModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let arr = model.data {
                    self?.prizeArr += arr
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    func awardUserRequest() {
        provider_Rank.rx.request(.awardUserList)
            .asObservable().mapModel(BaseModel<[LotteryModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let arr = model.data {
                    self?.userArr += arr
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    func winDrawRequest(_ wid: Int) {
        provider_Rank.rx.request(.winDraw(wid))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    return
                }
                self?.getUserGold { gold in
                    self?.goldView.goldCount.text = "\(gold) Golds"
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
}
